document.addEventListener('DOMContentLoaded', function() {
    const formRow = document.getElementById('config-form-row');
    let fullConfig = {}; // 用于存储完整的配置
    let allSignals = []; // 用于存储所有信号数据
    let itemsPerPage = 10; // 每页显示条数
    let currentPage = 1;

    // --- 新增：为每页显示条数下拉框绑定事件 ---
    const itemsPerPageSelect = document.getElementById('items-per-page-select');
    itemsPerPageSelect.addEventListener('change', function() {
        itemsPerPage = parseInt(this.value, 10);
        currentPage = 1; // 更改条数后回到第一页
        displayCurrentPage();
    });

    // 获取配置并生成表单
    fetch('/api/get_config')
        .then(response => response.json())
        .then(config => {
            if (config.error) {
                formRow.innerHTML = `<div class="alert alert-danger">${config.error}</div>`;
                return;
            }
            fullConfig = config; // 保存完整配置

            // 精确地创建并添加5个核心参数控件
            formRow.appendChild(createFormElement('start_date', 'Start Date', config.backtest_settings.start_date));
            formRow.appendChild(createFormElement('end_date', 'End Date', config.backtest_settings.end_date));
            formRow.appendChild(createFormElement('initial_cash', 'Initial Cash', config.backtest_settings.initial_cash));
            formRow.appendChild(createFormElement('trade_size', 'Trade Size', config.default_strategy_params.trade_size));
            formRow.appendChild(createFormElement('force_recache', 'Force Recache', config.data_settings.force_recache, 'checkbox'));
            
            // 在最右侧添加按钮
            const btnContainer = document.createElement('div');
            btnContainer.className = 'col-auto';
            btnContainer.innerHTML = `
                <button id="start-backtest-btn" class="btn btn-primary">
                    <i class="bi bi-play-fill"></i> 开始海选
                </button>`;
            formRow.appendChild(btnContainer);
            
            // 为新生成的按钮绑定事件
            bindStartButtonEvent(); 
        })
        .catch(error => {
            console.error('Error fetching config:', error);
            formRow.innerHTML = `<div class="alert alert-danger">无法加载配置文件。</div>`;
        });

    // 创建单个表单元素的辅助函数
    function createFormElement(id, labelText, value, type = 'text') {
        const col = document.createElement('div');
        col.className = 'col-auto';

        let inputHtml = '';
        if (type === 'checkbox') {
            inputHtml = `
                <div class="form-check form-switch mt-2">
                    <input class="form-check-input" type="checkbox" role="switch" id="param-${id}" name="${id}" ${value ? 'checked' : ''}>
                    <label class="form-check-label" for="param-${id}">${labelText}</label>
                </div>`;
        } else {
             inputHtml = `
                <div class="input-group">
                    <span class="input-group-text">${labelText}</span>
                    <input type="${id.includes('date') ? 'date' : 'number'}" class="form-control" id="param-${id}" name="${id}">
                </div>`;
        }
        col.innerHTML = inputHtml;
        
        // 设置初始值
        setTimeout(() => {
            const input = col.querySelector(`#param-${id}`);
            if (input.type === 'date') {
                input.value = `${String(value).slice(0,4)}-${String(value).slice(4,6)}-${String(value).slice(6,8)}`;
            } else if (input.type !== 'checkbox') {
                 input.value = value;
            }
        }, 0);

        return col;
    }

    // 绑定"开始海选"按钮事件的函数
    function bindStartButtonEvent() {
        const startBtn = document.getElementById('start-backtest-btn');
        const resultsContainer = document.getElementById('results-container');
        const loadingSpinner = document.getElementById('loading-spinner');
        const tableContainer = document.getElementById('results-table-container');

        startBtn.addEventListener('click', function() {
            // 1. 显示加载状态
            resultsContainer.style.display = 'block';
            loadingSpinner.style.display = 'block';
            tableContainer.innerHTML = ''; // 清空旧结果
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 海选中...';

            // 2. 从表单更新 fullConfig 对象
            const updatedConfig = JSON.parse(JSON.stringify(fullConfig)); // 创建一个深拷贝以避免修改原始数据
            
            const formElements = formRow.querySelectorAll('input, select');
            formElements.forEach(element => {
                const paramName = element.name;
                let value = element.value;

                if (element.type === 'checkbox') {
                    value = element.checked;
                } else if (element.type === 'date') {
                    value = value.replace(/-/g, ''); // YYYY-MM-DD -> YYYYMMDD
                } else if (!isNaN(value) && value.trim() !== '') {
                    value = Number(value);
                }

                // 在正确的嵌套结构中更新值
                if (updatedConfig.data_settings.hasOwnProperty(paramName)) {
                    updatedConfig.data_settings[paramName] = value;
                } else if (updatedConfig.backtest_settings.hasOwnProperty(paramName)) {
                    updatedConfig.backtest_settings[paramName] = value;
                } else if (updatedConfig.default_strategy_params.hasOwnProperty(paramName)) {
                    updatedConfig.default_strategy_params[paramName] = value;
                }
            });

            // 手动读取 forceRecache 的状态，并将其添加到请求体的顶层
            const forceRecacheSwitch = document.getElementById('param-force_recache');
            if(forceRecacheSwitch) {
                updatedConfig.forceRecache = forceRecacheSwitch.checked;
            }

            // 3. 发送API请求
            fetch('/api/run_signal_generation', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(updatedConfig), // 发送结构完整的配置对象
            })
            .then(response => response.json())
            .then(result => {
                // 4. 隐藏加载状态
                loadingSpinner.style.display = 'none';
                startBtn.disabled = false;
                startBtn.innerHTML = '<i class="bi bi-play-fill"></i> 开始海选';

                if (result.error) {
                    tableContainer.innerHTML = `<div class="alert alert-danger">海选失败: ${result.error}</div>`;
                    return;
                }
                
                // 5. 渲染结果表格（增强错误处理）
                try {
                    allSignals = result.data || [];
                    currentPage = 1;
                    itemsPerPage = parseInt(itemsPerPageSelect.value, 10);
                    displayCurrentPage();
                } catch (renderError) {
                    console.error("Failed to render results table:", renderError);
                    tableContainer.innerHTML = `<div class="alert alert-danger">渲染结果时出错: ${renderError.message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error during signal generation:', error);
                loadingSpinner.style.display = 'none';
                startBtn.disabled = false;
                startBtn.innerHTML = '<i class="bi bi-play-fill"></i> 开始海选';
                tableContainer.innerHTML = `<div class="alert alert-danger">请求失败，请检查网络或联系管理员。</div>`;
            });
        });
    }

    // --- 新增：显示当前页数据和分页控件 ---
    function displayCurrentPage() {
        const tableContainer = document.getElementById('results-table-container');
        const paginationControls = document.getElementById('pagination-controls');
        const totalCountText = document.getElementById('total-count-text');
        
        totalCountText.textContent = `共 ${allSignals.length} 条`;

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const pageData = allSignals.slice(startIndex, endIndex);

        // 渲染表格和分页
        renderResultsTable(pageData, tableContainer);
        renderPagination(allSignals.length, paginationControls);
    }

    // --- 新增：渲染分页控件 ---
    function renderPagination(totalItems, container) {
        container.innerHTML = '';
        const totalPages = Math.ceil(totalItems / itemsPerPage);

        if (totalPages <= 1) {
            return; // 如果只有一页或没有数据，则不显示分页控件
        }

        const nav = document.createElement('nav');
        const ul = document.createElement('ul');
        ul.className = 'pagination';

        // 上一页
        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        const prevLink = document.createElement('a');
        prevLink.className = 'page-link';
        prevLink.href = '#';
        prevLink.textContent = '上一页';
        prevLink.addEventListener('click', (e) => {
            e.preventDefault();
            if (currentPage > 1) {
                currentPage--;
                displayCurrentPage();
            }
        });
        prevLi.appendChild(prevLink);
        ul.appendChild(prevLi);

        // 页码
        // 为了简洁，我们只显示部分页码
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);
        
        if (currentPage <= 3) {
            endPage = Math.min(totalPages, 5);
        }
        if (currentPage > totalPages - 3) {
            startPage = Math.max(1, totalPages - 4);
        }

        if (startPage > 1) {
            const li = document.createElement('li');
            li.className = 'page-item disabled';
            li.innerHTML = `<span class="page-link">...</span>`;
            ul.appendChild(li);
        }

        for (let i = startPage; i <= endPage; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            const link = document.createElement('a');
            link.className = 'page-link';
            link.href = '#';
            link.textContent = i;
            link.addEventListener('click', (e) => {
                e.preventDefault();
                currentPage = i;
                displayCurrentPage();
            });
            li.appendChild(link);
            ul.appendChild(li);
        }

        if (endPage < totalPages) {
            const li = document.createElement('li');
            li.className = 'page-item disabled';
            li.innerHTML = `<span class="page-link">...</span>`;
            ul.appendChild(li);
        }

        // 下一页
        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        const nextLink = document.createElement('a');
        nextLink.className = 'page-link';
        nextLink.href = '#';
        nextLink.textContent = '下一页';
        nextLink.addEventListener('click', (e) => {
            e.preventDefault();
            if (currentPage < totalPages) {
                currentPage++;
                displayCurrentPage();
            }
        });
        nextLi.appendChild(nextLink);
        ul.appendChild(nextLi);

        container.appendChild(nav);
        nav.appendChild(ul);
    }
    
    // 渲染结果表格的函数
    function renderResultsTable(data, container) {
        if (!data || data.length === 0) {
            container.innerHTML = '<p class="text-muted">没有找到符合条件的信号。</p>';
            return;
        }

        let tableHtml = `
            <table class="table table-striped table-hover">
                <thead class="table-light">
                    <tr>
                        <th scope="col">序号</th>
                        <th scope="col">信号日期</th>
                        <th scope="col">股票编码</th>
                        <th scope="col">状态</th>
                        <th scope="col">创建时间</th>
                        <th scope="col">测试结果</th>
                        <th scope="col">操作</th>
                    </tr>
                </thead>
                <tbody>
        `;

        data.forEach((row, index) => {
            tableHtml += `
                <tr data-signal-id="${row.id}">
                    <td>${row['序号']}</td>
                    <td>${row['signal_date']}</td>
                    <td>${row['stock_code']}</td>
                    <td><span class="badge bg-secondary">${row['status']}</span></td>
                    <td>${row['created_at']}</td>
                    <td>${row['pnl_pct']}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary view-btn" data-bs-toggle="modal" data-bs-target="#tradeDetailModal">
                            查看
                        </button>
                    </td>
                </tr>
            `;
        });

        tableHtml += `
                </tbody>
            </table>
        `;

        container.innerHTML = tableHtml;
    }

    // --- 新增：为查看按钮添加事件监听（使用事件委托）---
    const resultsTableContainer = document.getElementById('results-table-container');
    resultsTableContainer.addEventListener('click', function(event) {
        // 检查被点击的元素是否是'查看'按钮
        if (event.target && event.target.classList.contains('view-btn')) {
            const row = event.target.closest('tr');
            const signalId = row.dataset.signalId;

            if (signalId) {
                console.log('查看按钮被点击, 信号ID:', signalId);
                
                // 更新模态框的标题
                const stockCode = row.cells[2].textContent; // 第3个单元格是股票代码
                document.getElementById('modal-stock-code').textContent = stockCode;
                
                const modalBody = document.querySelector('#tradeDetailModal .modal-body');
                modalBody.innerHTML = `
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">正在为信号ID ${signalId} 加载详细回测数据...</p>
                    </div>`;

                // 使用signalId去fetch详细数据并更新modal-body
                fetch(`/api/get_signal_details/${signalId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.error) {
                            modalBody.innerHTML = `<div class="alert alert-danger">获取详情失败: ${data.error}</div>`;
                            return;
                        }
                        // 使用 pre 和 code 标签来格式化显示JSON数据
                        modalBody.innerHTML = `
                            <h5>回测详情</h5>
                            <pre><code>${JSON.stringify(data.details, null, 2)}</code></pre>
                        `;
                    })
                    .catch(error => {
                        console.error('Error fetching signal details:', error);
                        modalBody.innerHTML = `<div class="alert alert-danger">请求详情数据时发生网络错误。</div>`;
                    });
            }
        }
    });
}); 